package com.atguigu.tingshu.order.service.impl;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2023-12-27 15:42
 */
@Slf4j
@Component
public class TestDealyMsgService {

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 项目启动后开启线程监听阻塞队列中消息
     */
    @PostConstruct
    public void fetchDalayMsg() {
        log.info("开启线程监听延迟消息：");
        //1.创建阻塞队列（当队列内元素超过上限，继续队列发送消息，进入阻塞状态/当队列中元素为空，继续拉取消息，进入阻塞状态）
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue("myBlockingQueue");
        //2.开启线程监听阻塞队列中消息
        new Thread(() -> {
            while (true) {
                String take = null;
                try {
                    take = blockingQueue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (StringUtils.isNotBlank(take)) {
                    log.info("监听到延迟消息：{}", take);
                }
            }
        }, "AA拉取延迟消息线程AA").start();
        ;
    }


}
